//
//  ARResponseModel.swift
//  AquaRaft
//
//  Created by 何启亮 on 2024/3/30.
//

import Foundation

enum AnyDecodable: Decodable, CustomStringConvertible, Encodable {
    case string(String)
    case array([AnyDecodable])
    case dictionary([String: AnyDecodable])
    case int(Int)
    case double(Double)
    case bool(Bool)

    init(from decoder: Decoder) throws {
        let container = try decoder.singleValueContainer()
        if let x = try? container.decode(String.self) {
            self = .string(x)
            return
        }
        if let x = try? container.decode([AnyDecodable].self) {
            self = .array(x)
            return
        }
        if let x = try? container.decode([String: AnyDecodable].self) {
            self = .dictionary(x)
            return
        }
        if let x = try? container.decode(Int.self) {
            self = .int(x)
            return
        }
        if let x = try? container.decode(Double.self) {
            self = .double(x)
            return
        }
        if let x = try? container.decode(Bool.self) {
            self = .bool(x)
            return
        }
        throw DecodingError.typeMismatch(AnyDecodable.self, DecodingError.Context(codingPath: decoder.codingPath, debugDescription: "Wrong type for DataValue"))
    }
    
    var description: String {
        switch self {
        case .string(let string):
            return string
        case .array(let array):
            return array.map { $0.description }.joined(separator: ", ")
        case .dictionary(let dictionary):
            return dictionary.map { "\($0.key): \($0.value.description)" }.joined(separator: ", ")
        case .int(let int):
            return String(int)
        case .double(let double):
            return String(double)
        case .bool(let bool):
            return String(bool)
        }
    }
    
    func encode(to encoder: Encoder) throws {
            var container = encoder.singleValueContainer()
            switch self {
            case .string(let string):
                try container.encode(string)
            case .array(let array):
                try container.encode(array)
            case .dictionary(let dictionary):
                try container.encode(dictionary)
            case .int(let int):
                try container.encode(int)
            case .double(let double):
                try container.encode(double)
            case .bool(let bool):
                try container.encode(bool)
            }
        }
}

struct ARResponseModel: Decodable {
    
    let code: Int
    let key: String?
    let msg: String?
    let data: AnyDecodable?
    
}
